package com.emm.yixun.website.controller.system;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;

@Controller
@RequestMapping("/system/account/")
public class AccountController extends BaseController<User>{
	@Autowired
	private UserServiceFacade userServiceFacade;

	@RequestMapping(value="findCurrentUser", method=RequestMethod.POST)
	@ResponseBody
	public AjaxRes findCurrentUser(){
		AjaxRes ar=getAjaxRes();
		try {
			User user=ShiroUtil.getCurrentUser();
			Response<User> response=userServiceFacade.findById(user.getId());
			if(response.isSuccess()){
				ar.setSucceed(response.getEntity());
			}
		} catch (Exception e) {
			logger.error(e.toString(),e);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}
	
	//修改
	@RequestMapping(value="editPwd", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  editPwd(String opwd,String npwd,String qpwd){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:account:editPwd"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
        		Response<Boolean> response=userServiceFacade.changePassword(user.getId(),opwd,npwd,qpwd);
				if(response.isSuccess() && response.getEntity()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(response.getResultMessage());
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	
	//修改
	@RequestMapping(value="editSkin", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  editSkin(String skin){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:account:editSkin"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
        		UserDto userDto=new UserDto();
        		userDto.setId(user.getId());
        		userDto.setSkin(skin);
        		Response<Integer> response=userServiceFacade.updateByPrimaryKey(userDto,false,true);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	
	//修改会员电话信息
	@RequestMapping(value="editUserLandLines", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes editUserLandLines(String landLines){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:account:editSkin"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
        		UserDto userDto=new UserDto();
        		userDto.setId(user.getId());
        		if(StringUtils.isNotBlank(landLines)){
        			Response<User> userResponse=userServiceFacade.findById(user.getId());
        			if(userResponse.isSuccess())
        			   user=userResponse.getEntity();
        			//当前用户电话信息
        			JSONArray userLandLinesArray=new JSONArray();
        			String userLandLines=user.getUserLandlines();
        			if(StringUtils.isNotBlank(userLandLines)){
        				userLandLinesArray=JSON.parseArray(userLandLines);
        			}
        			//修改后的电话信息
        			JSONArray array=JSON.parseArray(landLines);
        			//判断是否有重复
        			for(int i=0;i<array.size();i++){
        				JSONObject rowi=array.getJSONObject(i);
        				if(null==rowi)continue;
        				String phonei=rowi.getString("phone");
        				int count=0;
        				for(int j=0;j<array.size();j++){
        					JSONObject rowj=array.getJSONObject(j);
            				if(null==rowj)continue;
            				String phonej=rowj.getString("phone");
            				if(phonej.equals(phonei)){
            					count++;
            				}
        				}
        				if(count>1){
        					ar.setFailMsg("号码："+phonei+"重复");
        					return ar;
        				}
        			}
        			for(int i=0;i<array.size();i++){
        				JSONObject row=array.getJSONObject(i);
        				if(null==row)continue;
        				String phone=row.getString("phone");
        				Boolean isCheck=true;
        				for(int j=0;j<userLandLinesArray.size();j++){
        					String oldPhone=userLandLinesArray.getJSONObject(j).getString("phone");
        					if(oldPhone.equals(phone)){
        						isCheck=false;
        						break;
        					}
        				}
        				if(isCheck){
        					UserDto queryUserDto=new UserDto();
            				queryUserDto.setUserPhone(phone);
            				ResponseList<User> rlist=userServiceFacade.findByDto(queryUserDto);
            				if(rlist.isSuccess() && null!=rlist.getEntity() && rlist.getEntity().size()>0){
            					ar.setFailMsg("号码："+phone+"已存在");
            					return ar;
            				}
            				queryUserDto=new UserDto();
            				queryUserDto.setLikeLandlines(phone);
            				rlist=userServiceFacade.findByDto(queryUserDto);
            				if(rlist.isSuccess() && null!=rlist.getEntity() && rlist.getEntity().size()>0){
            					ar.setFailMsg("号码："+phone+"已存在");
            					return ar;
            				}
            				userLandLinesArray.add(row);
        				}
        				
        			}
        			userDto.setUserLandlines(landLines);
        		}
        		
        		Response<Integer> response=userServiceFacade.updateByPrimaryKey(userDto,false,true);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	
}
